package flc.ast.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.otaliastudios.cameraview.BitmapCallback;
import com.otaliastudios.cameraview.CameraException;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Audio;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;
import com.stark.picselect.PhotoSelectorBuilder;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.interfaces.OnSelectResultListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityRecCameraBinding;
import flc.ast.utils.AppSpUtils;
import flc.ast.view.CameraIndicator;
import stark.common.apis.ApiManager;
import stark.common.apis.base.ImgAnimalRet;
import stark.common.apis.base.ImgPlantRet;
import stark.common.base.IReqRetCallback;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.StkFlashUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class RecCameraActivity extends BaseAc<ActivityRecCameraBinding> {

    public static int type;
    private int mIndicator;//拍照模式
    //相机设置
    private boolean isFlash = false;//判断是否打开闪光灯

    @Override
    protected int onCreate() {
        return R.layout.activity_rec_camera;
    }

    @Override
    protected void initView() {
        mDataBinding.ivCameraBack.setOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.ivCameraFlash.setOnClickListener(this);
        mDataBinding.tvCameraBack.setOnClickListener(this);
        mDataBinding.ivCameraStart.setOnClickListener(this);
        mDataBinding.tvCameraImport.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        int id = v.getId();
        if (id == R.id.ivCameraFlash) {//闪光灯
            openFlash();
        } else if (id == R.id.tvCameraBack) {//返回
            getOnBackPressedDispatcher().onBackPressed();
        } else if (id == R.id.ivCameraStart) {//拍摄
            if (mDataBinding.cameraView.isTakingPicture()) return;
            mDataBinding.cameraView.takePictureSnapshot();
        } else if (id == R.id.tvCameraImport) {//相册导入
            getPermission();
        }
    }

    @Override
    protected void initData() {
        List<String> tabs = Arrays.asList(getString(R.string.plant_rec), getString(R.string.animal_rec));
        // 实现了 CameraIndicator.Tab 的对象
        List<CameraIndicator.Tab> tabList = new ArrayList<>();
        for (String tab : tabs) {
            tabList.add(() -> tab);
        }
        CameraIndicator.Tab[] map = tabList.toArray(new CameraIndicator.Tab[0]);
        // 将 tab 集合设置给 cameraIndicator，（binding.cameraIndicator 即 xml 布局里的控件）
        mDataBinding.cameraIndicator.setTabs(map);
        // 默认选中拍照
        mDataBinding.cameraIndicator.setCurrentIndex(type);
        mDataBinding.cameraIndicator.setOnSelectedChangedListener((index, tag) -> {
            mIndicator = index;
        });
        //初始化相机
        initCameraView();
    }

    //初始化相机
    private void initCameraView() {
        mDataBinding.cameraView.setMode(Mode.PICTURE);
        mDataBinding.cameraView.setAudio(Audio.OFF);
        mDataBinding.cameraView.setLifecycleOwner(this);
        int width = DensityUtil.getWith(mContext);
        int height = DensityUtil.getHeight(mContext);
        SizeSelector maxAreaSelector = SizeSelectors.maxArea(width * height);
        SizeSelector equalWidthSelector = SizeSelectors.withFilter(size -> size.getWidth() == width);
        mDataBinding.cameraView.setPictureSize(SizeSelectors.and(maxAreaSelector, equalWidthSelector));
        mDataBinding.cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {

            }

            @Override
            public void onCameraClosed() {
            }

            @Override
            public void onCameraError(@NonNull CameraException exception) {

            }

            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                int width = result.getSize().getWidth();
                int height = result.getSize().getHeight();
                int screenWidth = DensityUtil.getWith(mContext);
                int screenHeight = DensityUtil.getHeight(mContext);
                if (width * height > screenWidth * screenHeight) {
                    width = screenWidth;
                    height = screenHeight;
                }
                result.toBitmap(width, height, new BitmapCallback() {
                    @Override
                    public void onBitmapReady(@Nullable Bitmap bitmap) {
                        if (mIndicator == 0) {
                            plantRec(bitmap);
                        } else {
                            animalRec(bitmap);
                        }
                    }
                });
            }

            @Override
            public void onVideoRecordingStart() {

            }

            @Override
            public void onVideoRecordingEnd() {

            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {

            }
        });
    }

    private void getPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO)
                .reqPermissionDesc(getString(R.string.get_picture_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        getImage();
                    }
                }).request();
    }

    private void getImage() {
        PhotoSelectorBuilder.builder(this)
                .mode(PhotoConfig.Mode.PHOTO)
                .minCount(1)
                .maxCount(1)
                .listener(new OnSelectResultListener<List<SelectMediaEntity>>() {
                    @Override
                    public void onResult(List<SelectMediaEntity> data) {
                        ArrayList<String> pathList = new ArrayList<>();
                        for (SelectMediaEntity entity : data) {
                            pathList.add(entity.getTargetPath());
                        }
                        Bitmap bitmap = ImageUtils.getBitmap(pathList.get(0));
                        if (mIndicator == 0) {
                            plantRec(bitmap);
                        } else {
                            animalRec(bitmap);
                        }
                    }
                });
    }

    private void plantRec(Bitmap bitmap) {
        showDialog(getString(R.string.rec_ing));
        ApiManager.imgApi().identifyPlant(this, bitmap, new IReqRetCallback<List<ImgPlantRet>>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable List<ImgPlantRet> result) {
                dismissDialog();
                if (success) {
                    if (result != null && result.size() != 0) {
                        if (result.get(0).name.equals(getString(R.string.non_plant_name))) {
                            ToastUtils.showShort(R.string.no_find_data);
                        } else {
                            RecResultActivity.type = mIndicator;
                            RecResultActivity.sBitmap = bitmap;
                            RecResultActivity.sPlantRets = result;
                            startActivity(RecResultActivity.class);
                        }
                    } else {
                        ToastUtils.showShort(getString(R.string.rec_def));
                    }
                } else {
                    ToastUtils.showShort(getString(R.string.rec_def));
                }
            }
        });
    }

    private void animalRec(Bitmap bitmap) {
        showDialog(getString(R.string.rec_ing));
        ApiManager.imgApi().identifyAnimal(this, bitmap, new IReqRetCallback<List<ImgAnimalRet>>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable List<ImgAnimalRet> result) {
                dismissDialog();
                if (success) {
                    if (result != null && result.size() != 0) {
                        if (result.get(0).name.equals(getString(R.string.non_animal_name))) {
                            ToastUtils.showShort(R.string.no_find_data);
                        } else {
                            RecResultActivity.type = mIndicator;
                            RecResultActivity.sBitmap = bitmap;
                            RecResultActivity.sAnimRets = result;
                            startActivity(RecResultActivity.class);
                        }
                    } else {
                        ToastUtils.showShort(getString(R.string.rec_def));
                    }
                } else {
                    ToastUtils.showShort(getString(R.string.rec_def));
                }
            }
        });
    }

    //打开闪光灯
    private void openFlash() {
        if (isFlash) {
            isFlash = false;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.asgdk);
        } else {
            isFlash = true;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.asgd);
        }
        StkFlashUtil.setFlashlightStatus(isFlash);
    }

}